package com.seya.calculite.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class InputActivity extends Activity {

    Button btn_start;
    Bundle bundle;
    String location;
    TextView txt_location, txt_vehicle;
    //EditText txt_tag;
    AutoCompleteTextView txt_company, txt_tag;
    Context c;
    String vehicle, company, tag;
    SharedPreferences prefs;
    Spinner spinner;
    //CompanyParser[] companyParser;
    String[] companynamelist, taglist;
    private ArrayAdapter<String> companynameadapter, tagadapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        overridePendingTransition(R.anim.activity_open_translate,R.anim.activity_close_scale);
        setContentView(R.layout.activity_input);

        FontHelper.applyFont(this, findViewById(R.id.activity_main_root), "RobotoLight.ttf");
        txt_location=(TextView)findViewById(R.id.select_location);
        txt_vehicle=(TextView)findViewById(R.id.select_vehicle);
        txt_company=(AutoCompleteTextView)findViewById(R.id.select_company);
        txt_tag = (AutoCompleteTextView)findViewById(R.id.edit_tag);




        c = this;
        final TextDrawable textDrawable = new TextDrawable(c);

        spinner = (Spinner)findViewById(R.id.spn_vehicle);
        bundle = getIntent().getExtras();
        location = bundle.getString("location","Current location not available");
        txt_location.setText(location);


        companynamelist = parseJSON("CompanyListJSON.txt", "companylists", "name");
        taglist = parseJSON("TagListJSON.txt", "taglists", "tag");



        companynameadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
                companynamelist);
        tagadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
                taglist);
        txt_company.setAdapter(companynameadapter);
        txt_company.setThreshold(1);

        txt_tag.setAdapter(tagadapter);
        txt_tag.setThreshold(1);



        btn_start = (Button)findViewById(R.id.btn_start);
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vehicle = txt_vehicle.getText().toString();
                company = txt_company.getText().toString();
                tag = txt_tag.getText().toString();

                txt_tag.setError(null);
                txt_company.setError(null);
                txt_vehicle.setCompoundDrawablesWithIntrinsicBounds(getResources()
                                .getDrawable(R.drawable.ic_wheel), null,
                        getResources().getDrawable(R.drawable.ic_dropdown), null);
                txt_company.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        getResources().getDrawable(R.drawable.ic_portfolio), null);
                txt_tag.setCompoundDrawablesWithIntrinsicBounds(null, null,
                        getResources().getDrawable(R.drawable.ic_label), null);

                if(spinner.getSelectedItemPosition()==0) {
                    textDrawable.setText("Choose a vehicle");
                    textDrawable.setTextSize(12);
                    textDrawable.setTextColor(getResources().getColor(R.color.error));
                    txt_vehicle.setCompoundDrawablesWithIntrinsicBounds(getResources()
                            .getDrawable(R.drawable.ic_wheel), null,
                            textDrawable, null);
                    //txt_vehicle.setError("Choose a vehicle");
                } else if(company.equals("")) {
                    textDrawable.setText("Enter a company");
                    textDrawable.setTextSize(12);
                    textDrawable.setTextColor(getResources().getColor(R.color.error));
                    txt_company.setCompoundDrawablesWithIntrinsicBounds(null, null,
                            textDrawable, null);
                } else if(tag.equals("")) {
                    textDrawable.setText("Enter a tag");
                    textDrawable.setTextSize(12);
                    textDrawable.setTextColor(getResources().getColor(R.color.error));
                    txt_tag.setCompoundDrawablesWithIntrinsicBounds(null, null,
                            textDrawable, null);
                } else {
                    prefs = c.getSharedPreferences(SplashScreenActivity.
                            SHARED_PREFERENCES_NAME, MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putString(SplashScreenActivity.VEHICLE, vehicle);
                    editor.putString(SplashScreenActivity.COMPANY, company);
                    editor.putString(SplashScreenActivity.START_LOCATION, location);
                    editor.putString(SplashScreenActivity.TAG, tag);
                    //editor.putString();
                    editor.putLong(SplashScreenActivity.TIMER_SERVICE, SystemClock.uptimeMillis());
                    editor.commit();
                    Intent i = new Intent(getApplicationContext(), ProcessActivity.class);
                    startActivity(i);
                }
            }
        });

        txt_vehicle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    spinner.performClick();
            }
        });
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                txt_vehicle.setText(spinner.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    public String[] parseJSON(String filename,String jsonarray, String jsonobject) {
        // Reading text file from assets folder
        String[] jsonlists;
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(getAssets().open(
                    filename)));
            String temp;
            while ((temp = br.readLine()) != null)
                sb.append(temp);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close(); // stop reading
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String myjsonstring = sb.toString();

        try {
            JSONObject jsonObjMain = new JSONObject(myjsonstring);
            JSONArray jsonArray = jsonObjMain.getJSONArray(jsonarray);
            jsonlists = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObj = jsonArray.getJSONObject(i);
                jsonlists[i] = jsonObj.getString(jsonobject);
            }

            return jsonlists;

        } catch (JSONException e) {
            e.printStackTrace();
            return new String[0];
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if(resultCode == RESULT_OK){
                txt_vehicle.setText(data.getStringExtra("result"));
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.output, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        /*if (id == R.id.action_settings) {
            return true;
        }*/
        switch(id) {
            case R.id.action_history:
                Intent i = new Intent(InputActivity.this, HistoryActivity.class);
                startActivity(i);
                return true;
            case R.id.action_logout:
                SharedPreferences settings = c.getSharedPreferences(SplashScreenActivity.
                        SHARED_PREFERENCES_NAME, MODE_PRIVATE);
                settings.edit().clear().commit();
                SplashScreenActivity.loggingOut = true;
                i = new Intent(InputActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        //closing transition animations
        overridePendingTransition(R.anim.activity_open_scale,
                R.anim.activity_close_translate);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(SplashScreenActivity.loggingOut){
            finish();
        }
    }
}
